package com.chaoyi.util.schedule;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public enum ScheduledExecutorSingleton {
	
	INSTANCE;
	
	private final ScheduledExecutorService scheduledService = 
			Executors.newScheduledThreadPool(5, new ScheduledThreadFactory());
	
	public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit){
		 return scheduledService.scheduleWithFixedDelay(command, initialDelay, delay, unit);
	}
	
	public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit){
		return scheduledService.scheduleAtFixedRate(command, initialDelay, period, unit);
	}
	
	public ScheduledFuture<?> schedule(Runnable command,long delay,TimeUnit unit){
		return scheduledService.schedule(command, delay, unit);
	}
	
	public void shutdown(){
		scheduledService.shutdown();
	}
	
	private static class ScheduledThreadFactory implements ThreadFactory{
		private final AtomicInteger count = new AtomicInteger();
		
		@Override
		public Thread newThread(Runnable r) {
			Thread thread = new Thread(r);
			thread.setName("stat-scheduled"+"-"+count.incrementAndGet());
			thread.setUncaughtExceptionHandler(new ScheduledUncaughtExceptionHandler());
			thread.setDaemon(true);
			return thread;
		}
	}
	
	private static class ScheduledUncaughtExceptionHandler implements UncaughtExceptionHandler{
		private final Logger logger = LoggerFactory.getLogger(ScheduledUncaughtExceptionHandler.class);
		
		@Override
		public void uncaughtException(Thread t, Throwable e) {
			logger.error(t.getName()+" error:",e);
		}
		
	}
	
}
